// pages/cart/component/cart.js
import { reqCartList, reqUpdataChecked, reqCheckAllCart, reqAddCart, reqDelCart } from '@/api/cart'
import { swipeCellBehavior } from '@/behaviors/swipeCell'

import { ComponentWithStore } from 'mobx-miniprogram-bindings'
import { userStore } from '@/stores/userstore'
import { debounce } from 'miniprogram-licia'

const computedBehavior = require('miniprogram-computed').behavior
ComponentWithStore({
  // 注册behavior
  behaviors: [computedBehavior, swipeCellBehavior],
  storeBindings: {
    store: userStore,
    fields: ['token']
  },

  // 组件的初始数据
  data: {
    cartList: [],
    emptyDes: '还没有添加商品，快去添加吧～'
  },
  // computed: {
  //   selectAllStatus(data) {
  //     return data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1)
  //   }
  // },
  computed: {
    // 判断是否全选
    // computed 函数中不能访问 this ，只有 data 对象可供访问
    // 这个函数的返回值会被设置到 this.data.selectAllStatus 字段中
    selectAllStatus(data) {
      return data.cartList.length !== 0 && data.cartList.every((item) => item.isChecked === 1)
    },
    totalprice(data) {
      let totalprice = 0
      data.cartList.forEach((item) => {
        if (item.isChecked === 1) {
          totalprice += item.count * item.price
        }
      })
      return totalprice
      // return totalCart.reduce((sum, item) => {
      //   sum + item.count * item.price
      // }, 0)
      // const total = data.reduce((sum, item) => {
      //   sum + item.count * item.price
      // }, 0)
    }
  },
  // 组件的方法列表
  methods: {
    // 获取购物车数据
    async getCartList() {
      if (!this.data.token) {
        this.setData({
          emptyDes: '您尚未登录，点击登录获取更多权益',
          cartList: []
        })
        return
      }
      const { code, data: cartList } = await reqCartList()
      // console.log(res)
      // console.log(total)
      // let total = 0
      // data.forEach((item) => {
      //   total += item.count * item.price
      // })
      // console.log(code)
      // console.log(data)
      if (code === 200) {
        this.setData({
          cartList,
          emptyDes: cartList.length === 0 && '还没有添加商品，快去添加吧～'
        })
      }
    },
    // 商品状态updateChecked
    async updateChecked(e) {
      console.log(e)
      const { detail } = e
      const { id, index } = e.target.dataset
      const isChecked = detail ? 1 : 0
      const { code } = await reqUpdataChecked(id, isChecked)
      if (code === 200) {
        // this.getCartList()
        this.setData({
          [`cartList[${index}].isChecked`]: isChecked
        })
      }
    },
    // 全选与全不选
    async selectAllStatus(e) {
      const isChecked = e.detail ? 1 : 0
      // console.log(isChecked)
      const { code } = await reqCheckAllCart(isChecked)
      // console.log(code)
      if (code === 200) {
        // 方法一
        // this.getCartList()
        // 方法二
        const newCart = JSON.parse(JSON.stringify(this.data.cartList))
        newCart.forEach((item) => {
          item.isChecked = isChecked
        })
        this.setData({
          cartList: newCart
        })
      }
    },
    // 购买数量
    changeBuyNum: debounce(async function (e) {
      console.log(e)
      const newBuyNum = e.detail > 200 ? 200 : e.detail
      const { id, index, oldbuynum } = e.target.dataset
      // 正则验算数量是不是1~200之间的正整数
      const reg = /^([1-9]|[1-9]\d|1\d{2}|200)$/
      const regRes = reg.test(newBuyNum)

      // if (!regRes) {
      //   this.setData({
      //     [`cartList[${index}].count`]: oldbuynum
      //   })
      //   return
      // }
      // console.log(regRes)
      if (!regRes) {
        this.setData({
          [`cartList[${index}].count`]: oldbuynum
        })
        return
      }
      const diSCount = newBuyNum - oldbuynum
      if (diSCount === 0) return
      const res = await reqAddCart({ goodsId: id, count: diSCount })
      // console.log(res)
      if (res.code === 200) {
        this.setData({
          [`cartList[${index}].count`]: newBuyNum,
          [`cartList[${index}].isChecked`]: 1
        })
      }
    }, 500),

    // 删除购物车
    async delCartList(e) {
      const modals = await wx.modal({
        conten: '您确认要删除吗？'
      })
      if (modals) {
        await reqDelCart(e.target.dataset.id)
        this.getCartList()
      }
      // console.log(e)
    },
    // 跳转结算页面
    toOrder() {
      if (this.data.totalprice === 0) {
        wx.toast({
          title: '请选择需要购买的商品'
        })
        return
      }
      wx.navigateTo({
        url: '/modules/orderPayModule/pages/order/detail/detail'
      })
    },
    onShow() {
      console.log(this.data.token)
      this.getCartList()
      // this.selectAllStatus()
    },
    onHide() {
      this.onSwipeCellCommonClick()
    }
  }
})
